package gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author viento
 * @Date 2018/10/31 20:39
 * @Description TokenEffectiveFilter 判断Authorization是否有效
 * @Link 3576993219
 */
public class TokenEffectiveFilter extends ZuulFilter {
    public static String tokenHeader="parking_authority:auth:";
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        if (!ctx.sendZuulResponse()) {
            return false;
        }
        String requestUrl=ctx.getRequest().getServletPath();
        if (requestUrl.contains("/login/getUserPermission")){
            return true;
        }
        if (requestUrl.contains("/admin/token")||requestUrl.contains("login")||requestUrl.contains("register")||requestUrl.contains("/parking-inspection/assistant/pay")){
            return false;
        }
        if (requestUrl.contains("/parking-orders/index")||requestUrl.contains("/parking-orders/wx")){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        String author = (String) requestContext.get("Authorization");
        HttpServletRequest request = requestContext.getRequest();
        System.out.println(request.getQueryString());
        if (StringUtils.isNotEmpty(author)) {
            try {
                String[] authors = author.split(" ");
                if ("Basic".equals(authors[0])) {

                } else if ("Bearer".equals(authors[0])) {

                Boolean flag= (Boolean) redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
                        if (redisConnection.exists(redisTemplate.getKeySerializer().serialize(tokenHeader+authors[1]))){
                            return true;
                        }
                        return false;
                    });
                    if (!flag){
                        throw new Exception();
                    }
                    Jws<Claims> claims = Jwts.parser().setSigningKey("TREE_PARKING".getBytes("UTF-8")).parseClaimsJws(authors[1]);
                    Claims claim = claims.getBody();
                    List<String> curRoles = (List<String>) claim.get("scope");
                    requestContext.set("curRoles", curRoles);



                } else {


                }
            } catch (Exception e) {
                requestContext.setSendZuulResponse(false);
                requestContext.getResponse().setContentType("application/json;charset=UTF-8");
                requestContext.setResponseBody(JSON.toJSONString(""));

            }
        }

        return null;
    }

}
